<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\Response;
use app\common\model\Transfer as TransferModel;
use think\exception\ValidateException;
use app\common\model\User;

class Transfer extends Base
{

    /**
     * 转账规则
     * @return Response
     */
    public function rule(int $type=1): Response
    {
        $result['transfer_account'] = [
            [
                'title' => '余额',
                'type' => 'currency',
                'balance' => $this->user->assets->currency
            ],

        ];

        $result['transfer_factor'] = [
            'transfer_open' => $this->system['transfer_open'],
            'transfer_min' => $this->system['transfer_min'],
            'transfer_cost' => $this->system['transfer_cost'],
            'transfer_msg' => handleRichText($this->system['transfer_msg']),
        ];

        return Result::success('success', $result);
    }

    /**
     * 验证收款会员信息
     * @return Response
     */
    public function verify(): Response
    {
        $mobile = $this->request->param('mobile', '');
        $nickname = User::where('mobile', $mobile)->value('nickname');
        if ($nickname) {
            return Result::success('success', $nickname);
        } else {
            return Result::fail('会员不存在');
        }
    }

    /**
     * 转账
     * @return Response
     */
    public function save(): Response
    {
        if (!$this->user->pay_password) {
            return Result::fail('您尚未设置支付密码，请先去安全中心设置支付密码');
        }
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Transfer');
        } catch (ValidateException $e) {
            return Result::fail($e->getMessage());
        }
        return Result::fastReturn(TransferModel::add($param, $this->user, $this->system));
    }

    /**
     * 转账记录
     * @return Response
     */
    public function record(): Response
    {
        $type = $this->request->get('type', 1);
        $map = ['uid|take_uid' => $this->user->id, 'type'=>$type];
        $list = TransferModel::getPageList($map, 'id,account,uid,amount,cost,real_amount,take_uid,create_time', $this->getPage(), $this->getLimit(), false, ['take', 'user']);

        foreach ($list['data'] as &$v) {
            if ($v->uid == $this->user->id) {
                $v->trStatus = '转出';
                $v->trUser = $v->take->mobile;
            } else {
                $v->trStatus = '转入';
                $v->trUser = $v->user->mobile;
            }
            unset($v->uid);
            unset($v->take_uid);
            unset($v->take);
            unset($v->user);
        }
        return Result::fastReturn($list);
    }

}

